

package com.leon.datalink.web.controller;


import com.fasterxml.jackson.databind.node.ObjectNode;
import com.leon.datalink.core.common.Constants;
import com.leon.datalink.core.utils.JacksonUtils;
import com.leon.datalink.web.config.AuthConfig;
import com.leon.datalink.core.exception.impl.AccessException;
import com.leon.datalink.web.security.DatalinkAuthConfig;
import com.leon.datalink.web.service.UserService;
import com.leon.datalink.core.utils.BaseContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * User related methods entry.
 *
 * @author Leon
 */
@RestController
@RequestMapping("/api/auth/user")
@CrossOrigin(originPatterns = {"http://localhost:*", "http://127.0.0.1:*"}, allowCredentials = "true")
public class AuthController {

    @Autowired
    private AuthConfig authConfig;

    @Autowired
    private UserService userService;

    /**
     * Get user info.
     *
     * @return Current login user info
     */
    @GetMapping("/info")
    public Object getUsersInfo(HttpServletRequest request) {
        // Extract token from Authorization header
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);

            // Return user info based on token
            ObjectNode result = JacksonUtils.createEmptyJsonNode();
            result.put("code", 200);
            result.put("message", "success");

            ObjectNode userData = JacksonUtils.createEmptyJsonNode();
            userData.put("username", "admin");
            userData.put("description", "管理员");
            userData.set("permissions", JacksonUtils.createEmptyArrayNode().add("all"));
            userData.put("system", true);

            result.set("data", userData);
            return result;
        } else {
            ObjectNode result = JacksonUtils.createEmptyJsonNode();
            result.put("code", 401);
            result.put("message", "Unauthorized");
            return result;
        }
    }


    /**
     * Login to datalink
     *
     * <p>This methods uses username and password to require a new token.
     *
     * @param username username of user
     * @param password password
     * @param response http response
     * @param request  http request
     * @return new token of the user
     * @throws AccessException if user info is incorrect
     */
    @PostMapping("/login")
    public Object login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response,
                        HttpServletRequest request) throws AccessException {

        // Simple authentication for development
        if ("admin".equals(username) && "datalink".equals(password)) {
            String token = "dev-token-" + System.currentTimeMillis();
            response.addHeader(DatalinkAuthConfig.AUTHORIZATION_HEADER, DatalinkAuthConfig.TOKEN_PREFIX + token);

            ObjectNode response_data = JacksonUtils.createEmptyJsonNode();
            response_data.put(Constants.ACCESS_TOKEN, token);
            response_data.put(Constants.TOKEN_TTL, authConfig.getTokenValidityInSeconds());

            ObjectNode result = JacksonUtils.createEmptyJsonNode();
            result.put("code", 200);
            result.put("message", "success");
            result.set("data", response_data);
            return result;
        } else {
            throw new AccessException("Invalid credentials");
        }
    }


}
